﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.IO;
using System.Net;

namespace Chapter26.BasicWebClient
{
    /// <summary>
    /// WebRequestWithWebResponseWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WebRequestWithWebResponseWindow : Window
    {
        public WebRequestWithWebResponseWindow()
        {
            InitializeComponent();

            ReadWebSiteAsync();
        }

        private Task ReadWebSiteAsync()
        {
            return Task.Run(() =>
                {
                    var hao360WebRequest = WebRequest.Create("https://hao.360.cn");
                    var hao360WebResponse = hao360WebRequest.GetResponse();
                    var hao360DataStream = hao360WebResponse.GetResponseStream();
                    var line = string.Empty;
                    using (var hao360DataStreamReader = new StreamReader(hao360DataStream))
                    {
                        while ((line = hao360DataStreamReader.ReadLineAsync().Result) != null)
                        {
                            Dispatcher.Invoke(() => reqResListBox.Items.Add(line));
                            Task.Delay(300).Wait();
                        }
                    }
                });
        }

        private void ReadWebSite()
        {
            var hao360WebRequest = WebRequest.Create("https://hao.360.cn");
            var hao360WebRespnse = hao360WebRequest.GetResponse();
            var hao360DataStream = hao360WebRespnse.GetResponseStream();
            var line = string.Empty;
            using (var hao360DataStreamReader = new StreamReader(hao360DataStream))
            {
                while ((line = hao360DataStreamReader.ReadLine()) != null)
                {
                    reqResListBox.Items.Add(line);
                }
            }
        }
    }
}
